/**
 * *******************************************
 * user: zmq
 * describe: 负载均衡接口
 * created:
 * date: 2021/8/18
 * *******************************************
 */

import {pinus} from "pinus/";
let crc = require('crc');

export default class Dispatcher {
    /**
     * 求余的负载均衡
     * @param key
     * @param serverArray
     * @returns {*}
     */
    public static dispatch(key: string, serverArray: any) {
        let index = Math.abs(crc.crc32(key)) % serverArray.length;
        return serverArray[index];
    }


    /**
     * gate对connector进行负载均衡
     * @param account
     * @returns {*}
     */
    public static apportionConnector(account: string) {


        // 获取connectors的装备
        let connectors = pinus.app.getServersByType('connector');
        if (!connectors || connectors.length === 0) {       // 校验下connector的合法性
            return {};
        }


        if (connectors.length === 1) {
            return { clientHost: connectors[0].clientHost, clientPort: connectors[0].clientPort };
        }

        let res = this.dispatch(account, connectors);
        return { clientHost: res.clientHost, clientPort: res.clientPort };
    }
}
